#include "mainwindow.h"
#include <QDebug>
#include <QStyleFactory>
#include <QApplication>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      m_roleManager(new RoleManager(this)),
      m_autoSpeechCheckBox(nullptr),
      m_startButton(nullptr),
      m_customRoleButton(nullptr),
      m_modelComboBox(nullptr),
      m_roleComboBox(nullptr)
{
    setWindowTitle("智能对话助手");
    setMinimumSize(800, 600);  // 设置最小尺寸

    // 应用现代风格
    qApp->setStyle(QStyleFactory::create("Fusion"));

    // 设置调色板
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(240, 240, 240));
    palette.setColor(QPalette::WindowText, Qt::black);
    palette.setColor(QPalette::Base, Qt::white);
    palette.setColor(QPalette::AlternateBase, QColor(233, 231, 227));
    palette.setColor(QPalette::ToolTipBase, Qt::white);
    palette.setColor(QPalette::ToolTipText, Qt::black);
    palette.setColor(QPalette::Text, Qt::black);
    palette.setColor(QPalette::Button, QColor(240, 240, 240));
    palette.setColor(QPalette::ButtonText, Qt::black);
    palette.setColor(QPalette::BrightText, Qt::red);
    palette.setColor(QPalette::Highlight, QColor(100, 149, 237));
    palette.setColor(QPalette::HighlightedText, Qt::white);
    qApp->setPalette(palette);

    initUI();
    initRoles();
}

MainWindow::~MainWindow()
{
    delete m_roleManager;
}

void MainWindow::initUI()
{
    // 创建中央部件
    QWidget *centralWidget = new QWidget(this);
    centralWidget->setObjectName("centralWidget");
    setCentralWidget(centralWidget);

    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setContentsMargins(30, 30, 30, 30);
    mainLayout->setSpacing(20);

    // 模型选择区域
    QGroupBox *modelGroup = new QGroupBox("模型设置", centralWidget);
    modelGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *modelLayout = new QVBoxLayout(modelGroup);
    modelLayout->setSpacing(10);

    QLabel *modelLabel = new QLabel("选择模型:", modelGroup);
    m_modelComboBox = new QComboBox(modelGroup);
    m_modelComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_modelComboBox->addItem("qwen-2.5-3b_1.0 (本地模型)");
    m_modelComboBox->addItem("讯飞-Spark Max (云端模型)");

    modelLayout->addWidget(modelLabel);
    modelLayout->addWidget(m_modelComboBox);
    mainLayout->addWidget(modelGroup);

    // 角色选择区域
    QGroupBox *roleGroup = new QGroupBox("角色设置", centralWidget);
    roleGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *roleLayout = new QVBoxLayout(roleGroup);
    roleLayout->setSpacing(10);

    QLabel *roleLabel = new QLabel("选择角色:", roleGroup);
    m_roleComboBox = new QComboBox(roleGroup);
    m_roleComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 自定义角色按钮
    m_customRoleButton = new QPushButton("自定义角色", roleGroup);
    m_customRoleButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #F0F0F0;"
        "   border: 1px solid #D3D3D3;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #E0E0E0;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #D0D0D0;"
        "}");

    roleLayout->addWidget(roleLabel);
    roleLayout->addWidget(m_roleComboBox);
    roleLayout->addWidget(m_customRoleButton);
    mainLayout->addWidget(roleGroup);

    // 其他选项
    QGroupBox *optionGroup = new QGroupBox("其他选项", centralWidget);
    optionGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *optionLayout = new QVBoxLayout(optionGroup);

    m_autoSpeechCheckBox = new QCheckBox("自动语音输出", optionGroup);
    m_autoSpeechCheckBox->setChecked(false);

    optionLayout->addWidget(m_autoSpeechCheckBox);
    mainLayout->addWidget(optionGroup);

    //rag资料库查询

    QGroupBox *ragGroup = new QGroupBox("RAG资料库查询",centralWidget);
    ragGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *ragGroupLayout = new QVBoxLayout(ragGroup);

    m_ragSearchButton=new QPushButton("开始查询",ragGroup);
    m_ragSearchButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    ragGroupLayout->addWidget(m_ragSearchButton, 0, Qt::AlignCenter);

    m_ragSearchButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #F0F0F0;"
        "   border: 1px solid #D3D3D3;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #E0E0E0;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #D0D0D0;"
        "}");

    ragGroupLayout->addWidget(m_ragSearchButton);
    mainLayout->addWidget(ragGroup);


    // 开始按钮
    m_startButton = new QPushButton("开始对话", centralWidget);
    m_startButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #6495ED;"
        "   color: white;"
        "   border: none;"
        "   padding: 12px 24px;"
        "   border-radius: 6px;"
        "   font-size: 16px;"
        "   min-width: 120px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #4169E1;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #1E90FF;"
        "}");
    m_startButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    // 添加拉伸和按钮
    mainLayout->addStretch();
    mainLayout->addWidget(m_startButton, 0, Qt::AlignHCenter);

    // 连接信号槽
    connect(m_roleComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),this, &MainWindow::onRoleSelected);

    connect(m_customRoleButton, &QPushButton::clicked,this, &MainWindow::showCustomRoleDialog);

    connect(m_ragSearchButton,&QPushButton::clicked,this, &MainWindow::ragSearch);

    connect(m_startButton, &QPushButton::clicked,this, &MainWindow::startChat);

    resize(1360, 765);
}

void MainWindow::onRoleSelected(int index)
{
    if(index < 0) return;

    QString roleId = m_roleComboBox->itemData(index).toString();
    Role selectedRole = m_roles.value(roleId);

    qDebug() << "Selected role prompt:" << selectedRole.prompt;
    m_currentConfig.prompt = selectedRole.prompt;
}

void MainWindow::initRoles()
{
    if(!m_roleComboBox) return;

    m_roleComboBox->clear();

    // 加载内置角色
    if(m_roleManager && m_roleManager->loadRoles(":/roles/roles.json")) {
        QVector<Role> roles = m_roleManager->getRoles();
        for(const Role &role : roles) {
            m_roleComboBox->addItem(role.name, role.id);
            m_roles[role.id] = role;
        }
    }
    // 加载自定义角色
    QString customPath = QDir::currentPath() + "/KyAiData/custom_roles.json";
    if(m_roleManager && QFile::exists(customPath) && m_roleManager->loadRoles(customPath)) {
        QVector<Role> roles = m_roleManager->getRoles();
        for(const Role &role : roles) {
            m_roleComboBox->addItem(role.name, role.id);
            m_roles[role.id] = role;
        }setMinimumWidth(500);
    }
}

void MainWindow::showCustomRoleDialog()
{
    QDialog dialog(this);
    dialog.setWindowTitle("创建自定义角色");
    dialog.resize(800,450);

    QVBoxLayout *dialogLayout = new QVBoxLayout(&dialog);
    dialogLayout->setContentsMargins(20, 20, 20, 20);
    dialogLayout->setSpacing(15);

    QGroupBox *nameGroup = new QGroupBox("角色名称", &dialog);
    nameGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *nameLayout = new QVBoxLayout(nameGroup);
    nameLayout->setSpacing(5);

    // 角色名称输入框
    QLineEdit *nameEdit = new QLineEdit(&dialog);
    nameEdit->setPlaceholderText("例如: 心理咨询师");
    nameLayout->addWidget(nameEdit);

    dialogLayout->addWidget(nameGroup);

    QGroupBox *promptGroup= new QGroupBox("角色提示词",&dialog);
    promptGroup->setStyleSheet("QGroupBox { font-weight: bold; }");
    QVBoxLayout *promptLayout= new QVBoxLayout(promptGroup);
    promptLayout->setSpacing(5);

    // 角色提示词输入框
    QTextEdit *promptEdit = new QTextEdit(&dialog);
    promptEdit->setPlaceholderText("详细描述角色的特征和行为方式...");
    promptEdit->setMinimumHeight(200);
    promptLayout->addWidget(promptEdit);

    dialogLayout->addWidget(promptGroup);

    dialogLayout->addStretch();

    QPushButton *confirmButton=new QPushButton("确认", &dialog);
    QPushButton *cancelButton=new QPushButton("取消", &dialog);

    confirmButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #6495ED;"
        "   color: white;"
        "   border: none;"
        "   padding: 12px 24px;"
        "   border-radius: 6px;"
        "   font-size: 16px;"
        "   min-width: 120px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #4169E1;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #1E90FF;"
        "}");

    cancelButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #6495ED;"
        "   color: white;"
        "   border: none;"
        "   padding: 12px 24px;"
        "   border-radius: 6px;"
        "   font-size: 16px;"
        "   min-width: 120px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #4169E1;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #1E90FF;"
        "}");

    QHBoxLayout *confirmButtonLayout = new QHBoxLayout;
    confirmButtonLayout->addWidget(confirmButton);        // 默认左对齐
    confirmButtonLayout->addWidget(cancelButton);    // 默认左对齐
    confirmButtonLayout->setAlignment(Qt::AlignHCenter); // 水平居中对齐整个按钮组

    // 将水平布局添加到主布局（dialogLayout）的底部
    dialogLayout->addLayout(confirmButtonLayout);    // 默认会添加到末尾（底部）

    connect(confirmButton, &QPushButton::clicked, &dialog, &QDialog::accept);
    connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject);

    if(dialog.exec() == QDialog::Accepted) {
        QString name = nameEdit->text().trimmed();
        QString prompt = promptEdit->toPlainText().trimmed();

        if(!name.isEmpty() && !prompt.isEmpty()) {
            if(m_roleManager) {
                m_roleManager->saveCustomRole(name, prompt, "自定义角色：" + name);
                initRoles();
                QMessageBox::information(this, "成功", "自定义角色已添加");
            }
        } else {
            QMessageBox::warning(this, "警告", "角色名称和提示词不能为空");
        }
    }
    initRoles();
}

void MainWindow::startChat()
{
    qDebug()<<"currentIndex:"<<m_modelComboBox->currentIndex();
    switch (m_modelComboBox->currentIndex()) {
        case 0:
            m_currentConfig.modelName = "default";
            m_currentConfig.modelType = 0;
            break;
        case 1:
            m_currentConfig.modelName = "讯飞-Spark Max";
            m_currentConfig.modelType = 1;
            break;
        default:
            m_currentConfig.modelName = "default";
            m_currentConfig.modelType = 0;
            break;
    }

    m_currentConfig.autoSpeech = m_autoSpeechCheckBox->isChecked();

    // 创建并显示聊天窗口
    ChatWindow *chatWindow = new ChatWindow(m_currentConfig,this);
    chatWindow->setAttribute(Qt::WA_DeleteOnClose);
    chatWindow->show();

    // 隐藏主窗口
    //hide();
}

void MainWindow::ragSearch()
{

    RAGWindow *ragWindow = new RAGWindow(this);
    ragWindow->setAttribute(Qt::WA_DeleteOnClose);
    ragWindow->show();
    //hide();
}
